package com.yunjing.elasticjob.job;

import com.cxytiandi.elasticjob.annotation.ElasticJobConf;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.yunjing.elasticjob.entity.JobConfig;
import com.yunjing.elasticjob.entity.JobConfigRepository;
import com.yunjing.elasticjob.quartz.RemindJob;
import com.yunjing.elasticjob.service.JobService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author zhiqi.shao
 * @Date 2018/6/12 17:37
 */
@Slf4j
@ElasticJobConf(name = "SimpleJob1", cron = "0/10 * * * * ?", eventTraceRdbDataSource = "datasource")
public class SimpleJob1 implements SimpleJob {

    @Autowired
    private JobConfigRepository jobConfigRepository;

    @Autowired
    private JobService refreshJobService;

    /**
     * 执行分片任务
     *
     * @param context 分片信息上下文
     */
    @Override
    public void execute(ShardingContext context) {
        List<JobConfig> allJobConfigs = jobConfigRepository.findInitJobConfig(0);
        if(allJobConfigs==null||allJobConfigs.isEmpty()){
            return;
        }
        /**
         * 数据id%分片个数==当前分片就执行任务的刷新
         */
        allJobConfigs.forEach(jobConfig -> {
            if(jobConfig.getId()%context.getShardingTotalCount()==context.getShardingItem()){
                log.info("SimpleJob1 Sharding:{} accept " , context.getShardingItem());
                if(refreshJobService.putJob(jobConfig,RemindJob.class)){
                    jobConfigRepository.updateOverdueById(jobConfig.getId());
                }
            }
        });
    }




}
